#ifndef _MYTHREAD_HPP_
#define _MYTHREAD_HPP_
#pragma once
#include<iostream>
#include<string>
#include<functional>
#include<unistd.h>
#include<sys/types.h>
namespace ThreadModule
{
    //using func_t = std::function<void()>;
    using func_t = std::function<void(std::string name)>; // 传入线程名称作为参数
    static int number =1;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    class Mythread
    {
        private:
         static void *Routine(void*args)
          {
            Mythread *t = static_cast<Mythread *>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func(t->Name());
            return nullptr;
        }
    public:
        Mythread(func_t func):_func(func), _status(TSTATUS::NEW), _joinable(true)
        {
            _name = "Thread-" + std::to_string(number++);
            _pid = getpid();
        }
        bool start()//负责线程的创建
        {
             if (_status != TSTATUS::RUNNING)
            {
                int n = ::pthread_create(&_tid, nullptr, Routine, this); // TODO
                if (n != 0)
                    return false;
                return true;
            }
            return false;
        }
        bool join()//负责线程的等待
        {
            if (_joinable)
            {
                int n = ::pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        bool stop()//负责线程的取消
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        ~Mythread()
        {}
        bool detach()//负责线程的分离
        {
            if (_joinable)
            {
                int n = ::pthread_detach(_tid);
                if (n != 0)
                    return false;
                _joinable = false;
            }
        }

        std::string Name()
        {
            return _name;
        }
  
        private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable;//判断状态，我们之前讲了进程分离
        func_t _func;
        TSTATUS _status;
    };
}

#endif
